package com.cainiao.interceptor;

import com.cainiao.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class WebInterceptorTest implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求路径
        String requestURl =request.getRequestURL().toString(); ;
        //判断是否为登录请求
        if(requestURl.contains("/login")){
            log.info("登录请求放行");
            return true;
        }
        //获取请求头中的token
        String token = request.getHeader("token");
        //判断是否为空
        if(token==null||token.equals("")){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //验证token是否正确
        try{
            JwtUtils.parseJWT(token);
        }catch (Exception e){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        log.info("拿到令牌可以放行");
        return true;
    }

}
